package com.hqd.utils.pack.loader;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import sun.net.www.ParseUtil;

import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.Arrays;
import java.util.stream.Collectors;

/**
 * 加载依赖
 */
public class LibClassLoader extends URLClassLoader {
    private static Logger logger = Logger.getLogger(LibClassLoader.class);

    private LibClassLoader(URL[] urls) {
        super(urls);
    }

    /**
     * @param classPath jar文件所在路径
     * @return 自定义的类加载器
     * @throws IOException
     */
    public static ClassLoader newLibClassLoader(String classPath) {
        if (StringUtils.isBlank(classPath)) {
            logger.error("error:classPath is null or ''!");
            return null;
        }
        File file = new File(classPath);

        if (!file.exists() || !file.isDirectory()) {
            logger.error("error:Please check if your path is correct!");
            return null;
        }

        //获取所有的该目录下所有的jar文件
        File[] jars = Arrays.stream(file.listFiles())
                .filter((filePointer) -> filePointer.getName().endsWith(".jar"))
                .collect(Collectors.toList()).toArray(new File[0]);

        URL[] urls = new URL[jars.length];

        //将其所有的路径转换为URL
        for (int i = 0; i < urls.length; i++) {
            try {
                File f = jars[i].getCanonicalFile();
                urls[i] = ParseUtil.fileToEncodedURL(f);
            } catch (IOException e) {
                logger.error(e);
            }
        }

        return new LibClassLoader(urls);
    }
}